package com.zlz.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.zlz.server.annotation.OperateLog;
import com.zlz.server.aspect.OperateLogAspect;
import com.zlz.server.pojo.*;
import com.zlz.server.service.*;
import com.zlz.server.enums.OprLevel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author efire
 * @since 2021-01-31
 */
@RestController
@RequestMapping("/employee/basic")
@Slf4j
public class EmployeeController {
    @Resource
    private IEmployeeService iEmployeeService;

    @Resource
    private IPoliticsStatusService iPoliticsStatusService;

    @Resource
    private IPositionService iPositionService;

    @Resource
    private IDepartmentService iDepartmentService;

    @Resource
    private INationService iNationService;

    @Resource
    private IJoblevelService iJoblevelService;

    @ApiOperation("获取所有员工")
    @GetMapping("/")
    public RespBean getEmployee(@RequestParam(defaultValue = "1") Integer curPage,
                                @RequestParam(defaultValue = "10") Integer size,
                                Employee employee,
                                LocalDate[] beginDateScope) {
        RespPageBean respPageBean = iEmployeeService.getEmployeeByPage(curPage, size, employee, beginDateScope);
        return RespBean.success(respPageBean);
    }

    @ApiOperation("获取所有政治面貌")
    @GetMapping("/politicsstatus")
    public RespBean getAllPoliticsStatus() {
        return RespBean.success(iPoliticsStatusService.list());
    }

    @ApiOperation("获取所有职称")
    @GetMapping("/joblevels")
    public RespBean getAllJoblevels() {
        return RespBean.success(iJoblevelService.list());
    }

    @ApiOperation("获取所有民族")
    @GetMapping("/nations")
    public RespBean getAllNations() {
        return RespBean.success(iNationService.list());
    }

    @ApiOperation("获取所有职位")
    @GetMapping("/positions")
    public RespBean getAllPositions() {
        return RespBean.success(iPositionService.list());
    }

    @ApiOperation("获取所有部门")
    @GetMapping("/departments")
    public RespBean getAllDepartments() {
        return RespBean.success(iDepartmentService.getAllDepartments());
    }

    @ApiOperation("获取最大工号")
    @GetMapping("/maxWorkId")
    public RespBean getMaxWorkId() {
        return RespBean.success(iEmployeeService.getMaxWorkId());
    }

    @ApiOperation("添加员工")
    @PostMapping("/")
    @OperateLog(moduleName = "员工", operationName = "添加员工", level = OprLevel.LOW)
    public RespBean addEmp(@RequestBody Employee employee) {
        OperateLogAspect.setOperateTarget(employee.getName());
        OperateLogAspect.setOperateDetail(employee.toString());
        return iEmployeeService.addEmp(employee);
    }

    @ApiOperation("更新员工")
    @PutMapping("/")
    @OperateLog(moduleName = "员工", operationName = "更新员工信息", level = OprLevel.NORMAL)
    public RespBean updateEmp(@RequestBody Employee employee) {
        OperateLogAspect.setOperateTarget(employee.getName());
        if (iEmployeeService.updateById(employee)) {
            return RespBean.success("更新成功", null);
        }
        return RespBean.error("更新失败");

    }

    @ApiOperation("删除员工")
    @DeleteMapping("/{id}")
    @OperateLog(moduleName = "员工", operationName = "删除员工", level = OprLevel.HIGH)
    public RespBean addEmp(@PathVariable("id") Long id) {
        OperateLogAspect.setOperateTarget(id.toString());
        if (iEmployeeService.removeById(id)) {
            return RespBean.success("删除成功", null);
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation("导出员工数据")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void export(HttpServletResponse response) {
        List<Employee> employees = iEmployeeService.getEmployee(null);
        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, employees);
        try {
            // 流形式
            response.setHeader("content-type", "application/octet-stream");
            // 防止中文乱码
            response.setHeader("content-disposition", "attachment;filename=" +
                    URLEncoder.encode("员工表.xls", "UTF-8"));
        } catch (UnsupportedEncodingException e) {
           log.error("encode error.");
        }
        try(ServletOutputStream outputStream = response.getOutputStream();) {
            workbook.write(outputStream);
        } catch (IOException e) {
            log.error("some errors happened when writing");
        }
    }

    @ApiOperation("导入员工数据")
    @PostMapping("/import")
    public RespBean importEmployee(MultipartFile file) {
        ImportParams params = new ImportParams();
        // 去掉标题栏
        params.setTitleRows(1);
        List<Nation> nationList = iNationService.list();
        List<PoliticsStatus> politicsStatusList = iPoliticsStatusService.list();
        List<Joblevel> joblevelList = iJoblevelService.list();
        List<Position> positionList = iPositionService.list();
        List<Department> departmentList = iDepartmentService.list();
        try {
            List<Employee> employees = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            employees.forEach((employee -> {
                employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName())))
                        .getId());
                employee.setPoliticalId(politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee
                        .getPoliticsStatus().getName()))).getId());
                employee.setJobLevelId(joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel()
                        .getName()))).getId());
                employee.setPosId(positionList.get(positionList.indexOf(new Position(employee.getPosition()
                        .getName()))).getId());
                employee.setDepartmentId(departmentList.get(departmentList.indexOf(new Department(employee
                        .getDepartment().getName()))).getId());
            }));
            if (iEmployeeService.saveBatch(employees)) {
                return RespBean.success();
            }
        }  catch (Exception e) {
            log.error("导入失败", e);
        }
        return RespBean.error("导入失败");
    }
}
